﻿namespace EyeOpen.Data.EntityFramework
{
	using System.Configuration;
	using System.Data.Common;
	using System.Data.Entity;

	using EyeOpen.Domain;

	public abstract class EfUnitOfWork
		: DbContext, IUnitOfWork
	{
		protected EfUnitOfWork()
		{
		}

		protected EfUnitOfWork(ConnectionStringSettings connectionSettings)
			: this(connectionSettings.ProviderName, connectionSettings.ConnectionString)
		{
		}

		protected EfUnitOfWork(string connectionName)
			: base(connectionName)
		{
		}

		protected EfUnitOfWork(string providerName, string connectionString)
			: base(GetConnection(providerName, connectionString), true)
		{
		}

		public new IDatabase Database
		{
			get
			{
				return new DatabaseWrapper(this);
			}
		}

		public IRepository<T> Repository<T>() 
			where T : class, IEntity
		{
			return new Repository<T>(Set<T>());
		}

		public void Commit()
		{
			SaveChanges();
		}

		private static DbConnection GetConnection(string providerName, string connectionString)
		{
			var factory = DbProviderFactories.GetFactory(providerName);

			var connection = factory.CreateConnection();
			connection.ConnectionString = connectionString;

			return
				connection;
		}
	}
}